package Z.dailyExercise._0115;

public class _剑指Offer53I在排序数组中查找数字 {
    /**
     * 自解：二分先查找
     * pivot>value ,value在左边 high= mid-1
     * pivot<value value在右边 low = mid+1；
     * pivot= value 分别向左向右循环 直到遍历数据与value不想等
     *
     *
     * 题解：不断寻找相等
     * 相等一次 计数+1  再同时遍历 low mid-1以及mid+1，high
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        if (nums.length <1 || target <nums[0] || target >nums[nums.length-1]){
            return 0;
        }

        int low =0;
        int high = nums.length-1;
        int res=0;


        while (low<=high){
            int mid = low+(high-low)/2;
            if (nums[mid] < target){
                low = mid+1;
            }else if (nums[mid] > target){
                high = mid-1;
            }else {
                res +=1;
                int temp = mid;
                //left
                while (mid >= low && nums[mid-1] == target){
                    res++;
                    mid--;

                }

                //right
                while (temp <= high && nums[temp+1] == target){
                    res++;
                    temp++;
                }

                return res;

            }
        }

        return 0;



    }

}
